package com.initial.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.initial.config.ResultData;
import com.initial.entity.*;
import com.initial.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class JurisdictionController {
    @Resource
    private ResultData resultData;
    @Resource
    TbSystemRoleService tbSystemRoleService;
    @Resource
    TbSystemUserService tbSystemUserService;
    @Resource
    TbSystemUserRoleService tbSystemUserRoleService;
    @Resource
    TbSystemFunctionService tbSystemFunctionService;
    @Resource
    private TbSystemRoleFunction tbSystemRoleFunction;
    @Resource
    TbSystemRoleFunctionService tbSystemRoleFunctionService;

    /**
     * 首页左边的权限列表
     * */
    @RequestMapping("/index_menu")
    @ResponseBody
    public ResultData indexMenu(HttpSession session){
//      获取登录用户的ID
        TbSystemUser user = (TbSystemUser) session.getAttribute("user");
        Integer attribute = user.getId();
        TbSystemUserRole tbSystemUserRoles = tbSystemUserRoleService.selectListId(attribute);
        if (tbSystemUserRoles==null){
            resultData = ResultData.buildFailureResult("当前用户暂未获取系统操作权限，请与管理员联系!");
            return resultData;
        }
        Integer roleid = tbSystemUserRoles.getTbSystemRoles().getId();
        List<VMenu> tbSystemRoleFunctions = tbSystemRoleFunctionService.selectListId(roleid);

        if (tbSystemRoleFunctions==null || tbSystemRoleFunctions.isEmpty()){
            resultData = ResultData.buildFailureResult("当前用户暂未获取系统操作权限，请与管理员联系!");
            return resultData;
        }
        resultData = ResultData.buildSuccessResult("加载权限菜单成功",tbSystemRoleFunctions);
        return resultData;
    }

    /**
     * 去权限管理页面
     * */
    @RequestMapping("/torole")
    public String torole(){
        return "views/system/root_marketing";
    }

    /**
     * 去 用户列表
     * */
    @RequestMapping("message/tolist_user")
    public String tolist_user(){
        return "views/system/list_user";
    }
    /**
     * 用户列表分页
     * */
    @RequestMapping("system/user/UserAction_findByPage.action")
    @ResponseBody
    public Map<String,Object> UserAction_findByPage(Integer page,Integer rows){
        Map<String,Object> map=new HashMap<>();
        IPage<TbSystemUser> tbSystemUserIPage = tbSystemUserService.searchAllPage(new Page<>(page, rows));
        List<TbSystemUser> records = tbSystemUserIPage.getRecords();
        long total = tbSystemUserIPage.getTotal();
        map.put("result",records);;
        map.put("totalRows",total);
        return map;
    }
    /**
     * 去  为用户分配角色页面
     * */
    @RequestMapping("system/user/UserAction_assign")
    public String ToAction_assign(Integer id, Model model){
        model.addAttribute("userId",id);
        return "views/system/assign_user";
    }
    /**
     * 为用户分配角色  分页
     * */
    @RequestMapping("system/role/RoleAction_findAll")
    @ResponseBody
    public Map<String,Object> RoleAction_findAll(Integer page,Integer rows){
        Map<String,Object> map=new HashMap<>();
        System.out.println(page);
        System.out.println(rows);
        IPage<TbSystemRole> tbSystemRoleIPage = tbSystemRoleService.searchAllPage(new Page<>(page, rows));
        List<TbSystemRole> records = tbSystemRoleIPage.getRecords();
        long total = tbSystemRoleIPage.getTotal();
        map.put("result",records);;
        map.put("totalRows",total);
        return map;
    }
    /**
     * 为用户分配角色
     * */
    @RequestMapping("system/user/UserAction_updateRoles.action")
    @ResponseBody
    public Map<String,Object> RoleAction_assign(Integer userId,Integer ids){
        Map<String,Object> map=new HashMap<>();
        UpdateWrapper<TbSystemUserRole> updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("roleid",ids);
        updateWrapper.eq("userid",userId);
        boolean update = tbSystemUserRoleService.update(updateWrapper);
        if (update){
            map.put("success",true);
            map.put("msg","分配成功");
        }else {
            map.put("success",false);
            map.put("msg","分配失败");
        }
        return map;
    }
    /**
     * 删除 用户
     * */
    @RequestMapping("system/user/UserAction_remove.action")
    @ResponseBody
    public Map<String,Object> deleteUser(String[] ids){
        Map<String,Object> map=new HashMap<>();
        Integer integer=null;
        for (String id : ids) {
            Integer i = Integer.parseInt(id);
            integer = tbSystemUserService.deleteById(i);
        }
        if (integer==1){
            map.put("success",true);
            map.put("msg","删除成功");
        }else {
            map.put("success",false);
            map.put("msg","删除失败");
        }
        return map;
    }


    /**
     * 去 角色列表
     * */
    @RequestMapping("/message/tolist_role")
    public String tolist_role(){
        return "views/system/list_role";
    }
    /**
     * 去  角色分页
     * */
    @RequestMapping("system/role/RoleAction_findByPage.action")
    @ResponseBody
    public Map<String,Object> RoleAction_findByPage(Integer page ,Integer rows){
        Map<String,Object> map=new HashMap<>();
        IPage<TbSystemRole> tbSystemRoleIPage = tbSystemRoleService.searchAllPage(new Page<>(page, rows));
        long total = tbSystemRoleIPage.getTotal();
        List<TbSystemRole> records = tbSystemRoleIPage.getRecords();
        map.put("result",records);;
        map.put("totalRows",total);
        return map;
    }
    /**
     * 去  为角色分配权限页面
     * */
    @RequestMapping("/system/role/RoleAction_assign.action")
    public String RoleAction(Integer id, Model model){
        model.addAttribute("roleId",id);
        return "views/system/assign_role";
    }
    /**
     * 为角色分配权限 分页
     * */
    @RequestMapping("system/function/FunctionAction_findAll.action")
    @ResponseBody
    public Map<String,Object> FunctionAction_findAll(Integer page, Integer rows){
        Map<String,Object> map=new HashMap<String,Object>();
        IPage<TbSystemFunction> tbSystemFunctionIPage = tbSystemFunctionService.selectPage(new Page<>(page,rows));
        List<TbSystemFunction> records = tbSystemFunctionIPage.getRecords();
        long total = tbSystemFunctionIPage.getTotal();
        map.put("result",records);;
        map.put("totalRows",total);
        return map;
    }
    /**
     * 为角色分配权限
     * */
    @RequestMapping("system/user/RoleAction_updateRoles.action")
    @ResponseBody
    public Map<String,Object> RoleAction_updateRoles(String[] ids,Integer role){
        Map<String,Object> map=new HashMap<>();
        tbSystemRoleFunction.setRoleid(role);
        Integer integer=null;
        boolean save=false;
        for (String id : ids) {
            integer = Integer.parseInt(id);
            tbSystemRoleFunction.setFuncid(integer);

            System.out.println(tbSystemRoleFunction);

            boolean b = tbSystemRoleFunctionService.selectByIdRole(role, integer);
            if (b) {
                save = tbSystemRoleFunctionService.save(tbSystemRoleFunction);
            }
        }
        if (save){
            map.put("success",true);
            map.put("msg","添加成功");
        }else {
            map.put("success",false);
            map.put("msg","添加失败，权限可能已拥有");
        }
        return map;
    }
    /**
     * 删除 角色
     * */
    @RequestMapping("system/role/RoleAction_remove.action")
    @ResponseBody
    public Map<String,Object> deleteRole(String[] ids,HttpSession session){
        Map<String,Object> map=new HashMap<>();
        Integer userId = currentUserId(session);
        Integer integer=null;
        for (String id : ids) {
            Integer i = Integer.parseInt(id);
            integer = tbSystemRoleService.deleteById(i,userId);
        }
        if (integer==1){
            map.put("success",true);
            map.put("msg","删除成功");
        }else {
            map.put("success",false);
            map.put("msg","删除失败");
        }
        return map;
    }


    /**
     * 去 权限列表
     * */
    @RequestMapping("/message/tolist_function")
    public String tolist_function(){
        return "views/system/list_function";
    }
    /**
     * 去  权限分页
     * */
    @RequestMapping("system/function/Function_findAll")
    @ResponseBody
    public Map<String,Object> Function_findAll(Integer page,Integer rows){
        Map<String,Object> map=new HashMap<>();
        IPage<TbSystemFunction> tbSystemFunctionIPage = tbSystemFunctionService.searchAllPage(new Page<>(page, rows));
        List<TbSystemFunction> records = tbSystemFunctionIPage.getRecords();
        long total = tbSystemFunctionIPage.getTotal();
        map.put("result",records);;
        map.put("totalRows",total);
        return map;
    }
    /**
     * 删除 权限
     * */
    @RequestMapping("system/deleteFunction")
    @ResponseBody
    public Map<String,Object> deleteFunction(String[] ids,HttpSession session){
        Map<String,Object> map=new HashMap<>();
        Integer userId = currentUserId(session);
        Integer integer=null;
        for (String id : ids) {
            Integer i = Integer.parseInt(id);
            integer = tbSystemFunctionService.deleteById(i,userId);
        }
        if (integer==1){
            map.put("success",true);
            map.put("msg","删除成功");
        }else {
            map.put("success",false);
            map.put("msg","删除失败");
        }
        return map;
    }
    /**
     * 当前登录用户的 id
     * */
    public static Integer currentUserId(HttpSession session){
        TbSystemUser user = (TbSystemUser) session.getAttribute("user");
        Integer userId = user.getId();
        return userId;
    }

}
